using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Slobby.Client.UI {
    public class UserInterface {
        frmMain form;
        Controls.LoginPanel lip;
        Controls.ChatBox chat;

        public event EventHandler<LogInEventArgs> LogIn;
        public event Action<string> SendChat;
        public event EventHandler HostGame;

        private bool NoInvoke(MethodInvoker del) {
            if (form.InvokeRequired) {
                form.Invoke(del);
                return false;
            }
            return true;
        }

        public UserInterface() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            form = new frmMain();

            lip = new Controls.LoginPanel();
            lip.LogInClicked += new EventHandler<LogInEventArgs>(lip_LogInClicked);
            form.ChangeView(lip);

            chat = new Controls.ChatBox();
            chat.ChatMessage += chat_ChatMessage;

            form.HostClicked += new EventHandler(form_HostClicked);

            form.LoggedIn = false;
        }

        void form_HostClicked(object sender, EventArgs e) {
            HostGame(this, e);
        }

        public void ChatRecieved(string user, string text) {
            if (NoInvoke(delegate { ChatRecieved(user, text); })) {
                chat.AddLine(user, text);
            }
        }

        void lip_LogInClicked(object sender, LogInEventArgs e) {
            lip.ShowConnecting();
            if (LogIn != null) {
                LogIn(this, e);
            }
        }

        public void Run() {
            form.Show();
            form.FocusView();
            Application.Run(form);
        }

        public void Connected() {
            if (NoInvoke(delegate { Connected(); })) {
                form.ChangeView(chat);
                form.LoggedIn = true;
            }
        }

        void chat_ChatMessage(string obj) {
            string msg = obj;
            if (obj.StartsWith("/me ", StringComparison.InvariantCultureIgnoreCase)) {
                msg = "*" + msg.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries)[1] + "*";
            }
            SendChat(msg);
        }

        public void FailedConnect(string message) {
            if (NoInvoke(delegate { FailedConnect(message); })) {
                lip.HideConnecting();
                lip.StatusMessage = message;
            }
        }

        public void Disconnected(string reason) {
            if (NoInvoke(delegate { Disconnected(reason); })) {
                form.ChangeView(lip);
                lip.HideConnecting();
                lip.StatusMessage = reason;
                form.LoggedIn = false;
            }
        }
    }
}
